---
title: "Swift Syntax Comparison"
description: "Master Swift syntax by comparing it with JavaScript, covering variables, functions, control structures, and expressions."
---

## 1. Introduction

### Why Syntax Comparison Matters

As a JavaScript developer transitioning to Swift, understanding the syntax differences is crucial for writing clean, efficient code. Swift's syntax is designed to be safe, clear, and expressive, with strong emphasis on type safety and modern programming practices.

**Key Learning Objectives:**
- Understand Swift's type system and variable declarations
- Master function syntax and parameter handling
- Learn Swift's control structures and expressions
- Compare JavaScript and Swift coding patterns
- Develop Swift coding best practices

## 2. Variable Declarations and Types

### 2.1 Variable Declaration Comparison

Swift uses explicit type annotations and type inference, providing better safety than JavaScript's dynamic typing.

<UniversalEditor title="Variable Declaration Comparison" compare={true}>
```javascript !! js
// JavaScript variable declarations
let name = "John";           // String
const age = 25;              // Number
var isStudent = true;        // Boolean
let scores = [85, 90, 78];   // Array
let person = {               // Object
    name: "John",
    age: 25
};

// Type checking at runtime
console.log(typeof name);    // "string"
console.log(typeof age);     // "number"
console.log(typeof isStudent); // "boolean"
```

```swift !! swift
// Swift variable declarations
let name: String = "John"    // Explicit type annotation
let age = 25                 // Type inference (Int)
let isStudent = true         // Type inference (Bool)
let scores = [85, 90, 78]    // Type inference ([Int])
let person = [               // Dictionary literal
    "name": "John",
    "age": 25
]

// Type checking at compile time
print(type(of: name))        // String
print(type(of: age))         // Int
print(type(of: isStudent))   // Bool
```
</UniversalEditor>

### 2.2 Constants vs Variables

Swift makes a clear distinction between constants (`let`) and variables (`var`), similar to JavaScript's `const` and `let`.

<UniversalEditor title="Constants vs Variables" compare={true}>
```javascript !! js
// JavaScript constants and variables
const PI = 3.14159;          // Constant - cannot be reassigned
let radius = 5;              // Variable - can be reassigned
var diameter = 10;           // Variable (function-scoped)

// Attempting to reassign constant (will cause error)
// PI = 3.14; // TypeError: Assignment to constant variable

radius = 7;                  // Valid reassignment
console.log(`Area: ${PI * radius * radius}`);
```

```swift !! swift
// Swift constants and variables
let pi = 3.14159             // Constant - cannot be reassigned
var radius = 5               // Variable - can be reassigned

// Attempting to reassign constant (will cause compile error)
// pi = 3.14 // Error: Cannot assign to value: 'pi' is a 'let' constant

radius = 7                   // Valid reassignment
print("Area: \(pi * Double(radius) * Double(radius))")
```
</UniversalEditor>

### 2.3 Type Annotations

Swift allows explicit type annotations for better code clarity and compiler optimization.

<UniversalEditor title="Type Annotations" compare={true}>
```javascript !! js
// JavaScript - dynamic typing
let message = "Hello";       // String
let count = 42;              // Number
let isActive = true;         // Boolean

// Type can change at runtime
message = 123;               // Now it's a number
count = "forty-two";         // Now it's a string
isActive = 1;                // Now it's a number (truthy)

console.log(typeof message); // "number"
console.log(typeof count);   // "string"
console.log(typeof isActive); // "number"
```

```swift !! swift
// Swift - static typing with type annotations
let message: String = "Hello"    // Explicit String type
let count: Int = 42              // Explicit Int type
let isActive: Bool = true        // Explicit Bool type

// Type cannot change - these would cause compile errors:
// message = 123        // Error: Cannot assign value of type 'Int' to type 'String'
// count = "forty-two"  // Error: Cannot assign value of type 'String' to type 'Int'
// isActive = 1         // Error: Cannot assign value of type 'Int' to type 'Bool'

print(type(of: message))     // String
print(type(of: count))       // Int
print(type(of: isActive))    // Bool
```
</UniversalEditor>

## 3. Functions and Methods

### 3.1 Function Declaration Comparison

Swift functions have more explicit syntax with parameter labels and return types.

<UniversalEditor title="Function Declaration Comparison" compare={true}>
```javascript !! js
// JavaScript function declarations
function greet(name) {
    return `Hello, ${name}!`;
}

// Arrow function
const greetArrow = (name) => {
    return `Hello, ${name}!`;
};

// Function with multiple parameters
function calculateArea(width, height) {
    return width * height;
}

// Function with default parameters
function greetWithDefault(name = "World") {
    return `Hello, ${name}!`;
}

console.log(greet("Alice"));           // "Hello, Alice!"
console.log(calculateArea(10, 5));     // 50
console.log(greetWithDefault());       // "Hello, World!"
```

```swift !! swift
// Swift function declarations
func greet(name: String) -> String {
    return "Hello, \(name)!"
}

// Function with multiple parameters
func calculateArea(width: Double, height: Double) -> Double {
    return width * height
}

// Function with default parameters
func greetWithDefault(name: String = "World") -> String {
    return "Hello, \(name)!"
}

// Function with external parameter names
func greet(person name: String) -> String {
    return "Hello, \(name)!"
}

print(greet(name: "Alice"))            // "Hello, Alice!"
print(calculateArea(width: 10, height: 5)) // 50.0
print(greetWithDefault())              // "Hello, World!"
print(greet(person: "Bob"))            // "Hello, Bob!"
```
</UniversalEditor>

### 3.2 Function Types and Closures

Swift treats functions as first-class citizens with explicit function types.

<UniversalEditor title="Function Types and Closures" compare={true}>
```javascript !! js
// JavaScript function types and closures
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;

// Function as variable
const operation = add;
console.log(operation(5, 3)); // 8

// Function that returns a function
const createCalculator = (operation) => {
    return (a, b) => operation(a, b);
};

const calculator = createCalculator(add);
console.log(calculator(10, 5)); // 15

// Higher-order function
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(x => x * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
```

```swift !! swift
// Swift function types and closures
let add: (Int, Int) -> Int = { a, b in a + b }
let multiply: (Int, Int) -> Int = { a, b in a * b }

// Function as variable
let operation = add
print(operation(5, 3)) // 8

// Function that returns a function
func createCalculator(operation: @escaping (Int, Int) -> Int) -> (Int, Int) -> Int {
    return operation
}

let calculator = createCalculator(operation: add)
print(calculator(10, 5)) // 15

// Higher-order function
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { $0 * 2 }
print(doubled) // [2, 4, 6, 8, 10]
```
</UniversalEditor>

## 4. Control Structures

### 4.1 Conditional Statements

Swift's `if` statements are similar to JavaScript but with stronger type checking.

<UniversalEditor title="Conditional Statements" compare={true}>
```javascript !! js
// JavaScript conditional statements
let age = 18;
let hasLicense = true;

if (age >= 18) {
    console.log("You are an adult");
} else if (age >= 13) {
    console.log("You are a teenager");
} else {
    console.log("You are a child");
}

// Truthy/falsy values
let name = "";
let count = 0;
let isActive = false;

if (name) {
    console.log("Name is provided");
} else {
    console.log("Name is empty");
}

if (count) {
    console.log("Count is non-zero");
} else {
    console.log("Count is zero");
}

// Ternary operator
let status = age >= 18 ? "adult" : "minor";
console.log(status);
```

```swift !! swift
// Swift conditional statements
let age = 18
let hasLicense = true

if age >= 18 {
    print("You are an adult")
} else if age >= 13 {
    print("You are a teenager")
} else {
    print("You are a child")
}

// Swift requires explicit boolean expressions
let name = ""
let count = 0
let isActive = false

if !name.isEmpty {
    print("Name is provided")
} else {
    print("Name is empty")
}

if count > 0 {
    print("Count is non-zero")
} else {
    print("Count is zero")
}

// Ternary operator
let status = age >= 18 ? "adult" : "minor"
print(status)
```
</UniversalEditor>

### 4.2 Switch Statements

Swift's `switch` statement is much more powerful than JavaScript's, supporting pattern matching.

<UniversalEditor title="Switch Statements" compare={true}>
```javascript !! js
// JavaScript switch statement
let day = "Monday";

switch (day) {
    case "Monday":
        console.log("Start of work week");
        break;
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
        console.log("Mid week");
        break;
    case "Friday":
        console.log("TGIF!");
        break;
    case "Saturday":
    case "Sunday":
        console.log("Weekend!");
        break;
    default:
        console.log("Invalid day");
}

// Switch with fall-through (requires explicit break)
let grade = "B";
switch (grade) {
    case "A":
        console.log("Excellent");
        break;
    case "B":
        console.log("Good");
        break;
    case "C":
        console.log("Average");
        break;
    default:
        console.log("Needs improvement");
}
```

```swift !! swift
// Swift switch statement with pattern matching
let day = "Monday"

switch day {
case "Monday":
    print("Start of work week")
case "Tuesday", "Wednesday", "Thursday":
    print("Mid week")
case "Friday":
    print("TGIF!")
case "Saturday", "Sunday":
    print("Weekend!")
default:
    print("Invalid day")
}

// Swift switch with range matching
let score = 85
switch score {
case 90...100:
    print("A")
case 80..<90:
    print("B")
case 70..<80:
    print("C")
case 60..<70:
    print("D")
case 0..<60:
    print("F")
default:
    print("Invalid score")
}

// Swift switch with tuple matching
let point = (2, 0)
switch point {
case (0, 0):
    print("Origin")
case (_, 0):
    print("On x-axis")
case (0, _):
    print("On y-axis")
case (-2...2, -2...2):
    print("Near origin")
default:
    print("Somewhere else")
}
```
</UniversalEditor>

### 4.3 Loops

Swift provides multiple loop constructs with different use cases.

<UniversalEditor title="Loops Comparison" compare={true}>
```javascript !! js
// JavaScript loops
const numbers = [1, 2, 3, 4, 5];

// For loop
for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}

// For...of loop (iterate over values)
for (const num of numbers) {
    console.log(num);
}

// For...in loop (iterate over keys)
const person = { name: "John", age: 30 };
for (const key in person) {
    console.log(`${key}: ${person[key]}`);
}

// While loop
let count = 0;
while (count < 5) {
    console.log(count);
    count++;
}

// Do...while loop
let i = 0;
do {
    console.log(i);
    i++;
} while (i < 3);

// Array methods
numbers.forEach(num => console.log(num));
const doubled = numbers.map(num => num * 2);
const evens = numbers.filter(num => num % 2 === 0);
```

```swift !! swift
// Swift loops
let numbers = [1, 2, 3, 4, 5]

// For-in loop (iterate over values)
for num in numbers {
    print(num)
}

// For-in loop with range
for i in 0..<numbers.count {
    print(numbers[i])
}

// For-in loop with stride
for i in stride(from: 0, to: 10, by: 2) {
    print(i) // 0, 2, 4, 6, 8
}

// While loop
var count = 0
while count < 5 {
    print(count)
    count += 1
}

// Repeat-while loop (equivalent to do-while)
var i = 0
repeat {
    print(i)
    i += 1
} while i < 3

// Dictionary iteration
let person = ["name": "John", "age": "30"]
for (key, value) in person {
    print("\(key): \(value)")
}

// Array methods
numbers.forEach { print($0) }
let doubled = numbers.map { $0 * 2 }
let evens = numbers.filter { $0 % 2 == 0 }
```
</UniversalEditor>

## 5. Operators and Expressions

### 5.1 Basic Operators

Swift operators are similar to JavaScript but with stronger type safety.

<UniversalEditor title="Basic Operators" compare={true}>
```javascript !! js
// JavaScript operators
let a = 10;
let b = 3;

// Arithmetic operators
console.log(a + b);  // 13
console.log(a - b);  // 7
console.log(a * b);  // 30
console.log(a / b);  // 3.333...
console.log(a % b);  // 1
console.log(a ** b); // 1000

// Assignment operators
let x = 5;
x += 3;  // x = x + 3
x -= 2;  // x = x - 2
x *= 4;  // x = x * 4
x /= 2;  // x = x / 2

// Comparison operators
console.log(a == b);   // false
console.log(a != b);   // true
console.log(a > b);    // true
console.log(a >= b);   // true

// Logical operators
let isTrue = true;
let isFalse = false;
console.log(isTrue && isFalse);  // false
console.log(isTrue || isFalse);  // true
console.log(!isTrue);            // false
```

```swift !! swift
// Swift operators
let a = 10
let b = 3

// Arithmetic operators
print(a + b)  // 13
print(a - b)  // 7
print(a * b)  // 30
print(a / b)  // 3 (integer division)
print(a % b)  // 1
print(pow(Double(a), Double(b))) // 1000.0

// Assignment operators
var x = 5
x += 3  // x = x + 3
x -= 2  // x = x - 2
x *= 4  // x = x * 4
x /= 2  // x = x / 2

// Comparison operators
print(a == b)   // false
print(a != b)   // true
print(a > b)    // true
print(a >= b)   // true

// Logical operators
let isTrue = true
let isFalse = false
print(isTrue && isFalse)  // false
print(isTrue || isFalse)  // true
print(!isTrue)            // false

// Range operators
let range1 = 1...5    // Closed range (1, 2, 3, 4, 5)
let range2 = 1..<5    // Half-open range (1, 2, 3, 4)
```
</UniversalEditor>

### 5.2 String Operations

Swift provides powerful string interpolation and manipulation capabilities.

<UniversalEditor title="String Operations" compare={true}>
```javascript !! js
// JavaScript string operations
let firstName = "John";
let lastName = "Doe";

// String concatenation
let fullName = firstName + " " + lastName;
console.log(fullName); // "John Doe"

// Template literals
let greeting = `Hello, ${firstName} ${lastName}!`;
console.log(greeting); // "Hello, John Doe!"

// String methods
let message = "Hello World";
console.log(message.length);           // 11
console.log(message.toUpperCase());    // "HELLO WORLD"
console.log(message.toLowerCase());    // "hello world"
console.log(message.indexOf("World")); // 6
console.log(message.substring(0, 5));  // "Hello"
console.log(message.replace("World", "Swift")); // "Hello Swift"

// String comparison
let str1 = "apple";
let str2 = "Apple";
console.log(str1 === str2); // false
console.log(str1.toLowerCase() === str2.toLowerCase()); // true
```

```swift !! swift
// Swift string operations
let firstName = "John"
let lastName = "Doe"

// String concatenation
let fullName = firstName + " " + lastName
print(fullName) // "John Doe"

// String interpolation
let greeting = "Hello, \(firstName) \(lastName)!"
print(greeting) // "Hello, John Doe!"

// String methods
let message = "Hello World"
print(message.count)                    // 11
print(message.uppercased())             // "HELLO WORLD"
print(message.lowercased())             // "hello world"
print(message.contains("World"))        // true
print(message.prefix(5))                // "Hello"
print(message.replacingOccurrences(of: "World", with: "Swift")) // "Hello Swift"

// String comparison
let str1 = "apple"
let str2 = "Apple"
print(str1 == str2) // false
print(str1.lowercased() == str2.lowercased()) // true

// Multi-line strings
let multiLine = """
    This is a
    multi-line
    string in Swift
    """
print(multiLine)
```
</UniversalEditor>

## 6. Comments and Documentation

### 6.1 Comment Styles

Both languages support similar comment styles, but Swift has additional documentation features.

<UniversalEditor title="Comments and Documentation" compare={true}>
```javascript !! js
// JavaScript comments and documentation

// Single-line comment
let name = "John"; // This is a variable

/*
 * Multi-line comment
 * This is a block comment
 * that can span multiple lines
 */

/**
 * JSDoc comment for function documentation
 * @param {string} name - The name to greet
 * @param {number} age - The age of the person
 * @returns {string} A greeting message
 */
function greetPerson(name, age) {
    return `Hello ${name}, you are ${age} years old`;
}

// Inline comment
let result = 5 + 3; // Calculate sum
```

```swift !! swift
// Swift comments and documentation

// Single-line comment
let name = "John" // This is a variable

/*
 * Multi-line comment
 * This is a block comment
 * that can span multiple lines
 */

/**
 * Swift documentation comment
 * - Parameter name: The name to greet
 * - Parameter age: The age of the person
 * - Returns: A greeting message
 */
func greetPerson(name: String, age: Int) -> String {
    return "Hello \(name), you are \(age) years old"
}

// Inline comment
let result = 5 + 3 // Calculate sum

// MARK: - Section marker for code organization
// MARK: Properties
let title = "My App"

// MARK: Methods
func doSomething() {
    // Implementation
}

// TODO: - Reminder for future work
// TODO: Implement error handling

// FIXME: - Mark for bug fixes
// FIXME: This needs to be optimized
```
</UniversalEditor>

## 7. Practice Exercises

### Exercise 1: Variable and Function Practice

<UniversalEditor title="Exercise 1: Basic Syntax" compare={true}>
```javascript !! js
// JavaScript exercise
// 1. Declare variables for a person's information
let personName = "Alice";
let personAge = 25;
let personCity = "New York";

// 2. Create a function that calculates BMI
function calculateBMI(weight, height) {
    return weight / (height * height);
}

// 3. Create a function that returns a formatted string
function formatPersonInfo(name, age, city) {
    return `${name} is ${age} years old and lives in ${city}`;
}

// 4. Test the functions
let bmi = calculateBMI(70, 1.75);
console.log(`BMI: ${bmi.toFixed(2)}`);
console.log(formatPersonInfo(personName, personAge, personCity));
```

```swift !! swift
// Swift exercise
// 1. Declare variables for a person's information
let personName: String = "Alice"
let personAge: Int = 25
let personCity: String = "New York"

// 2. Create a function that calculates BMI
func calculateBMI(weight: Double, height: Double) -> Double {
    return weight / (height * height)
}

// 3. Create a function that returns a formatted string
func formatPersonInfo(name: String, age: Int, city: String) -> String {
    return "\(name) is \(age) years old and lives in \(city)"
}

// 4. Test the functions
let bmi = calculateBMI(weight: 70, height: 1.75)
print("BMI: \(String(format: "%.2f", bmi))")
print(formatPersonInfo(name: personName, age: personAge, city: personCity))
```
</UniversalEditor>

### Exercise 2: Control Flow Practice

<UniversalEditor title="Exercise 2: Control Flow" compare={true}>
```javascript !! js
// JavaScript control flow exercise
function gradeCalculator(score) {
    if (score >= 90) {
        return "A";
    } else if (score >= 80) {
        return "B";
    } else if (score >= 70) {
        return "C";
    } else if (score >= 60) {
        return "D";
    } else {
        return "F";
    }
}

function numberAnalyzer(number) {
    let result = "";
    
    if (number > 0) {
        result += "Positive ";
    } else if (number < 0) {
        result += "Negative ";
    } else {
        result += "Zero ";
    }
    
    if (number % 2 === 0) {
        result += "even";
    } else {
        result += "odd";
    }
    
    return result;
}

// Test the functions
console.log(gradeCalculator(85)); // "B"
console.log(numberAnalyzer(7));   // "Positive odd"
console.log(numberAnalyzer(-4));  // "Negative even"
```

```swift !! swift
// Swift control flow exercise
func gradeCalculator(score: Int) -> String {
    switch score {
    case 90...100:
        return "A"
    case 80..<90:
        return "B"
    case 70..<80:
        return "C"
    case 60..<70:
        return "D"
    case 0..<60:
        return "F"
    default:
        return "Invalid score"
    }
}

func numberAnalyzer(number: Int) -> String {
    var result = ""
    
    if number > 0 {
        result += "Positive "
    } else if number < 0 {
        result += "Negative "
    } else {
        result += "Zero "
    }
    
    if number % 2 == 0 {
        result += "even"
    } else {
        result += "odd"
    }
    
    return result
}

// Test the functions
print(gradeCalculator(score: 85)) // "B"
print(numberAnalyzer(number: 7))   // "Positive odd"
print(numberAnalyzer(number: -4))  // "Negative even"
```
</UniversalEditor>

## 8. Key Takeaways

### 8.1 Syntax Differences Summary

| Feature | JavaScript | Swift | Key Difference |
|---|---|---|---|
| **Variable Declaration** | `let/const/var` | `let/var` | Swift uses `let` for constants, no `const` |
| **Type System** | Dynamic typing | Static typing | Swift requires explicit types or type inference |
| **Function Parameters** | No labels | External parameter names | Swift uses parameter labels for clarity |
| **String Interpolation** | `${variable}` | `\(variable)` | Different syntax for string interpolation |
| **Switch Statement** | Basic matching | Pattern matching | Swift supports complex pattern matching |
| **Loop Syntax** | `for...of`, `for...in` | `for...in` | Swift's `for...in` is more versatile |
| **Type Checking** | Runtime | Compile-time | Swift catches errors before execution |

### 8.2 Best Practices

1. **Use Type Annotations**: Explicitly declare types for better code clarity
2. **Prefer Constants**: Use `let` instead of `var` when possible
3. **Use Parameter Labels**: Make function calls more readable
4. **Leverage Pattern Matching**: Use Swift's powerful switch statements
5. **Write Clear Documentation**: Use Swift's documentation comments
6. **Follow Naming Conventions**: Use camelCase for variables and functions
7. **Use String Interpolation**: Prefer `\(variable)` over concatenation

### 8.3 Common Pitfalls

1. **Forgetting Type Annotations**: Swift's type inference is good, but explicit types help
2. **Mixing `let` and `var`**: Use `let` for constants, `var` only when needed
3. **Ignoring Parameter Labels**: They make code more readable
4. **Not Using Pattern Matching**: Swift's switch statements are powerful
5. **String vs Character**: Swift distinguishes between String and Character types

## 9. Next Steps

In the next module, we'll explore Swift's type system in detail, including:
- Optional types and nil safety
- Type inference and type annotations
- Type aliases and type conversion
- Type safety programming practices

This foundation in Swift syntax will prepare you for the more advanced concepts in the upcoming modules. 